<template>
  <section class="form-box">
    <div class="form-base">
      <div class="from-base-item">
        <span class="lable">接口类型</span>
        <el-select v-model="ifType" placeholder="请选择">
          <el-option label="RESTFUL_API" value="HTTP"></el-option>
          <el-option label="SQL" value="DB"></el-option>
          <el-option label="JAVA定制" value="JAR"></el-option>
        </el-select>
      </div>
      <div class="from-base-item">
        <span class="lable">接口文档</span>
        <el-upload
          class="upload-demo"
          :headers="importHeaders"
          :action="`${BASEURL}/attachment/upload`"
          :on-success="handleSuccess"
        >
          <el-button type="primary">上传</el-button>
        </el-upload>
        <el-button type="text" v-show="doc">
          <a
            :href="doc"
            target="_blank"
            class="download"
            rel="noopener noreferrer"
            >接口文档-{{ queryLastName(doc) }}</a
          >
        </el-button>
        <el-input v-model="doc" v-show="false" />
      </div>
    </div>
    <TypeOne v-if="ifType == 'HTTP'" />
    <TypeTwo v-if="ifType == 'DB'" />
    <TypeThree v-if="ifType == 'JAR'" />

    <div class="request-table">
      <h5>出参格式转换</h5>
      <ResponseTable
        :tableData="outputFormatList"
        @callRequest="
          (value) => {
            outputFormatList = value;
          }
        "
      />
    </div>

    <div class="test-result">
      <h4 class="divider">
        测试结果
        <el-button
          type="primary"
          class="fr"
          @click="testApi"
          :loading="contactLoading"
          >测试接口</el-button
        >
      </h4>
      <div class="code-box json-format">
        <pre v-html="syntaxHighlight(testData)"></pre>
      </div>
    </div>
    <div class="test-result">
      <h4 class="divider">
        出参文档
        <span class="introductions fr">自动生成出参文档格式</span>
        <!-- <span class="introductions">
          <a href="/file/standard.md" download="参标准化功能说明.md"
            >出参标准化功能说明</a
          ></span
        > -->
        <!-- <el-button type="primary" class="fr" @click="standardApi"
          >自动生成出参文档格式</el-button
        > -->
      </h4>
      <table class="pure-table">
        <thead>
          <tr class="outpramas-header">
            <th>参数名称 <span class="required">*</span></th>
            <th>参数中文名称</th>
            <th>参数类型<span class="required">*</span></th>
            <th width="60">必须</th>
            <th>示例</th>
            <th>说明</th>
            <th width="60">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in requsetStu" :key="index">
            <td>
              <el-input
                v-model="item.paramName"
                placeholder="请输入"
              ></el-input>
            </td>
            <td>
              <el-input
                v-model="item.paramNameCn"
                placeholder="请输入"
              ></el-input>
            </td>
            <td>
              <el-select
                v-model="item.paramType"
                placeholder="请选择"
                filterable
                allow-create
                clearable
              >
                <el-option
                  v-for="(item, index) in options"
                  :key="index"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </td>
            <td>
              <el-checkbox v-model="item.required"></el-checkbox>
            </td>
            <td>
              <el-input
                v-model="item.demoValue"
                placeholder="请输入"
              ></el-input>
            </td>
            <td>
              <el-input v-model="item.memo" placeholder="请输入"></el-input>
            </td>
            <td><span class="del" @click="delRow(index)">删除</span></td>
          </tr>
          <tr>
            <td colspan="4">
              <el-button type="primary" @click="addRequestRow"
                >+增加参数</el-button
              >
            </td>
          </tr>
        </tbody>
      </table>
      <div class="code-box json-format">
        <pre v-html="syntaxHighlight(stuData)"></pre>
      </div>
    </div>
    <div class="footer">
      <el-divider></el-divider>
      <el-button type="primary" @click="editRow(2)" plain>上一步</el-button>
      <el-button type="primary" @click="onSubmit('save')">暂存</el-button>
      <el-button type="primary" @click="onSubmit('submit')">提交审核</el-button>
    </div>
  </section>
</template>

<script>
import TypeOne from "./TypeOne.vue";
import TypeTwo from "./TypeTwo.vue";
import TypeThree from "./TypeThree.vue";
import { reactive, ref, onMounted, defineComponent } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { ElMessageBox, ElMessage } from "element-plus";
import { submitOrSave, ifcallVersion, sendStandard } from "@/api/service.js";
import ResponseTable from "@/views/system/auth/components/ResponseTable.vue";
import {
  deepClone,
  syntaxHighlight,
  objIsAttr,
  html2Escape,
  obj2String,
  arr2StringJoinIndex,
  queryLastName,
} from "@/utils/index.js";
export default defineComponent({
  components: { TypeOne, TypeTwo, TypeThree, ResponseTable },
  emits: ["callEdit"],
  setup(props, ctx) {
    const store = useStore();
    const route = useRoute();
    const router = useRouter();
    const ifType = ref("HTTP");
    let doc = ref("");
    const testResult = ref("");
    const contactLoading = ref(false);
    const options = reactive([
      "Text",
      "Object",
      "Array",
      "String",
      "Number",
      "Integer",
      "Float",
      "Double",
      "File",
      "Date",
      "DateTime",
      "TimeStamp",
      "Boolean",
    ]);
    const requsetStu = reactive([]);
    const outputFormatList = ref([]);
    const testData = ref({});
    const stuData = ref({});
    const addRequestRow = () => {
      requsetStu.push({ paramName: "" });
    };
    const delRow = (index) => {
      requsetStu.splice(index, 1);
    };
    const testApi = async () => {
      contactLoading.value = true;
      testData.value = "";
      let data = pushStore();
      try {
        let res = await ifcallVersion(data);
        testData.value = html2Escape(res);
        contactLoading.value = false;
      } catch (e) {
        contactLoading.value = false;
      }
    };
    const standardApi = async () => {
      let params = {
        json: JSON.stringify(testData.value),
        outParamsList: requsetStu,
      };
      let res = await sendStandard(params);
      stuData.value = res;
      // console.log(res);
    };
    // 暂存
    const pushStore = () => {
      requsetStu.map((item, index) => {
        item.displayOrder = index;
      });
      store.commit("app/PUT_SERVICE_3", ifType.value);
      store.commit("app/PUT_SERVICE_DOC", doc.value);
      store.commit("app/PUT_SERVICE_OUT_PARAMS", requsetStu);
      console.log(outputFormatList.value);
      store.commit("app/PUT_SERVICE_OUT_FORMATLIST", outputFormatList.value);

      let data = deepClone(store.state.app.serviceBody);
      data.ifParam.adptIfCfgHttp.inParamsJson = obj2String(
        data.ifParam.adptIfCfgHttp.inParamsJson
      );
      data.ifParam.adptIfCfgDb.inParamsJson = arr2StringJoinIndex(
        data.ifParam.adptIfCfgDb.inParamsJson
      );
      return data;
    };
    // 选择接口类型
    const selectTypeObj = (ifType) => {
      let str = "";
      if (ifType == "HTTP") {
        str = "adptIfCfgHttp";
      } else if (ifType == "DB") {
        str = "adptIfCfgDb";
      } else if (ifType == "JAR") {
        str = "adptIfCfgJar";
      }
      return str;
    };
    // 提交审核
    const onSubmit = async (type) => {
      let data = pushStore();
      // console.log(data);
      const { ifType, ifParam } = data;
      let status = true;
      let fieldList = {
        HTTP: ["callTimeout", "httpMethod", "ifUrl", "inParamsJson", "srcId"],
        DB: ["sqlStmt", "srcId"],
        JAR: ["classFullName", "jarFile"],
      };
      let arr = fieldList[ifType];
      let typeObj = ifParam[selectTypeObj(ifType)];
      arr.map((item) => {
        status = status && objIsAttr(typeObj, item);
      });
      if (!status) {
        ElMessage.error("请补充必填字段");
        return false;
      } else {
        // console.log(data);
        let res = await submitOrSave(type, data);
        let status = res.status == 200;
        ElMessage({
          type: status ? "success" : "error",
          message: status ? "操作成功" : "操作失败",
        });
        if (status) {
          router.push("/service/audit");
        }
        // console.log("state：", store.state.app.serviceBody);
      }
      // console.log("submit!");
    };
    const editRow = (index) => {
      ctx.emit("callEdit", index);
      // tableData.value.splice(index, 1);
    };
    let editMode = route.name == "EditService";

    // 上传参数
    const BASEURL = ref(import.meta.env.VITE_APP_BASE_API);
    const importHeaders = ref({
      Authorization: store.getters.token,
      ORG: store.getters.currentOrgId,
    });
    // 上传成功
    const handleSuccess = ({ status, data, message }) => {
      if (status === 200) {
        // 请求成功 上传成功
        doc.value = data.fileUrl;
        ElMessage.success("上传成功");
      } else {
        // 请求成功 上传失败
        ElMessage.error(message);
      }
    };
    onMounted(() => {
      if (editMode) {
        ifType.value = store.state.app.serviceBody.ifType || "HTTP";
        doc.value = store.state.app.serviceBody.doc;
        // 出参标准化写入;
        let outParamsList = store.state.app.serviceBody.outParamsList || [];
        requsetStu.push(...outParamsList);
        // 出参格式转换写入
        let list = store.state.app.serviceBody.outputFormatList || [];
        outputFormatList.value.push(...list);
      }
    });
    return {
      ifType,
      testResult,
      requsetStu,
      ResponseTable,
      options,
      editRow,
      onSubmit,
      addRequestRow,
      testApi,
      contactLoading,
      syntaxHighlight,
      testData,
      stuData,
      standardApi,
      delRow,
      doc,
      BASEURL,
      importHeaders,
      handleSuccess,
      queryLastName,
      outputFormatList
    };
  },
});
</script>
<style lang="scss" scoped>
.outpramas-header {
  font-size: 14px;
}
</style>
